package com.alliky.core.widget;

import android.graphics.Rect;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ConvertUtils;

/**
 * @Author: wxianing
 * @CreateDate: 2022/6/22 22:32
 * @Description: java类作用描述
 */
public class MyGridItemDecoration extends RecyclerView.ItemDecoration {
    private int spanCount; // 每行个数
    private int decoration; // 间距
    private boolean includeEdge; // 是否需要左右，上下分割线
    private int total; // item总共的间隔
    private int[] left; // left 数组
    private int[] right; // right 数组

    public MyGridItemDecoration(int spanCount, int decoration, boolean includeEdge) {
        this.spanCount = spanCount;
        this.decoration = ConvertUtils.dp2px(decoration);
        this.includeEdge = includeEdge;
        if (includeEdge) {
            total = decoration + Math.round(decoration * 1f / spanCount);
        } else {
            total = Math.round(decoration * (spanCount - 1) * 1f / spanCount);
        }
        left = new int[spanCount];
        right = new int[spanCount];
        for (int i = 0; i < spanCount; i++) {
            if (i == 0) {
                if (includeEdge) {
                    left[i] = decoration;
                } else {
                    left[i] = 0;
                }
            } else {
                left[i] = decoration - (total - left[i - 1]); // 后一列的left = decoration - (total - 上一列的left)
            }
            right[i] = total - left[i];
        }
    }

    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view,
                               @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        int position = parent.getChildAdapterPosition(view);
        int column = position % spanCount;// 计算这个child 处于第几列
        outRect.left = left[column];
        outRect.right = right[column];

        if (includeEdge) {
            if (position < spanCount) { // 第一行设置top
                outRect.top = decoration;
            }
            outRect.bottom = decoration; // 设置bottom
        } else {
            if (position >= spanCount) {
                outRect.top = decoration; // 非第一行设置top
            }
        }
    }

}
